package org.jeecg.modules.nurse_user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.nurse_dept.entity.NurseDept;
import org.jeecg.modules.nurse_home_addr.entity.NurseHomeAddr;
import org.jeecg.modules.nurse_home_addr.service.INurseHomeAddrService;
import org.jeecg.modules.nurse_user.entity.*;
import org.jeecg.modules.nurse_user.service.*;
import org.jeecg.modules.nurse_user.vo.NurseUserPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 用户管理
 * @Author: jeecg-boot
 * @Date: 2024-06-09
 * @Version: V1.0editByWeChat
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/nurse_user/nurseUser")
@Slf4j
public class NurseUserController extends JeecgController<NurseUser, INurseUserService> {

    @Autowired
    private INurseUserService nurseUserService;

    @Autowired
    private INurseUserFamilyService nurseUserFamilyService;

    @Autowired
    private INurseUserAddrService nurseUserAddrService;

    @Autowired
    private INurseUserIntegralService nurseUserIntegralService;

    @Autowired
    private INurseUserSpecialService nurseUserSpecialService;

    @Autowired
    private INurseHomeAddrService nurseHomeAddrService;




    @Autowired
    private RedisUtil redisUtil;

    @Value("${wechat.nurse.login-url:}")
    private String loginUrl;

    @Value("${wechat.nurse.username:}")
    private String username;

    @Value("${wechat.nurse.password:}")
    private String password;

    @Value("${wechat.nurse.appid}")
    private String appid;

    @Value("${wechat.nurse.appsecret}")
    private String appsecret;

    /**
     * 刷新用户优惠劵
     *
     * @param userId
     * @return
     */
    @AutoLog(value = "刷新用户优惠劵")
    @ApiOperation(value = "刷新用户优惠劵", notes = "刷新用户优惠劵")
    @GetMapping(value = "/refreshSpecial")
    public Result<?> refreshSpecial(@RequestParam(name = "userId") String userId) {

        List<NurseUserSpecial> nurseUserSpecialList = nurseUserSpecialService.queryByNotExpire(userId);

        for (NurseUserSpecial nurseUserSpecial : nurseUserSpecialList) {
            nurseUserSpecial.setUpdateBy(null);
            nurseUserSpecial.setUpdateTime(null);
            nurseUserSpecial.setCreateTime(null);
            nurseUserSpecial.setCreateBy(null);
        }

        nurseUserSpecialService.saveBatch(nurseUserSpecialList);
        return Result.OK("刷新成功");
    }

    /**
     * 通过userId查询
     *
     * @param userId
     * @return
     */
    @AutoLog(value = "用户管理-通过userId查询优惠劵")
    @ApiOperation(value = "用户管理-通过userId查询优惠劵", notes = "用户管理-通过userId查询优惠劵")
    @GetMapping(value = "/getSpecialList")
    public Result<?> getSpecialList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize, @RequestParam(name = "userId") String userId, @RequestParam(name = "isvalid", defaultValue = "0", required = false) String isvalid) {

        QueryWrapper<NurseUserSpecial> queryWrapper = new QueryWrapper<NurseUserSpecial>();
        queryWrapper.eq("user_id", userId);

        if (isvalid.equals("1")) {
            queryWrapper.eq("status", "1");
            queryWrapper.apply("NOW() >= begin_time");
            queryWrapper.apply("NOW() <= end_time");
            //queryWrapper.apply("CONVERT(VARCHAR (23), getDate(), 120) >= CONVERT(VARCHAR (23), begin_time, 120) ");
           // queryWrapper.apply("CONVERT(VARCHAR (23), getDate(), 120) <= CONVERT(VARCHAR (23), end_time, 120) ");
        }
        queryWrapper.orderByAsc("status");

        Page<NurseUserSpecial> page = new Page<>(pageNo, pageSize);

        IPage<NurseUserSpecial> pageList = nurseUserSpecialService.page(page, queryWrapper);

        return Result.OK(pageList);
    }

    @AutoLog(value = "用户管理-用户登录")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping(value = "/login")
    public Result<?> login(@RequestBody NurseUser nurseUser) {

        if (!redisUtil.hasKey(nurseUser.getOpenid())) {
            return Result.error("登录失败！未查询到用户信息");
        } else {
            redisUtil.del(nurseUser.getOpenid());
        }

//        nurseUserService.getOne(new QueryWrapper<NurseUser>().eq("openid", nurseUser.getOpenid()));
//        if (oConvertUtils.isEmpty(nurseUser)) {
//            return Result.error("登录失败！未查询到用户信息");
//        }
        JSONObject req = new JSONObject();

        req.put("username", username);
        req.put("password", password);

        JSONObject res = RestUtil.post(loginUrl, req);

        res = res.getJSONObject("result");

        if (oConvertUtils.isEmpty(res)) {
            return Result.error("登录失败！未请求到用户信息");
        }

        String token = res.getString("token");

        if (oConvertUtils.isEmpty(token)) {
            return Result.error("登录失败！未请求到token");
        }
//        res.clear();
//		res.put("nurseUser", nurseUser);
//        res.put("token", token);

        return Result.OK(token);
    }


    /**
     * 通过openid查询
     *
     * @param openid
     * @return
     */
//    @AutoLog(value = "用户管理-通过openid查询")
    @ApiOperation(value = "用户管理-通过openid查询", notes = "用户管理-通过openid查询")
    @GetMapping(value = "/queryByOpenId")
    public Result<?> queryByOpenId(@RequestParam(name = "openid", required = true) String openid) {
        NurseUser nurseUser = nurseUserService.getOne(new QueryWrapper<NurseUser>().eq("openid", openid));

        if (nurseUser == null) {
            return Result.OK("未找到对应数据");
        }

        if (nurseUser.getStatus().equals("0")) {
            return Result.error("该用户已被禁用,请联系相关工作人员！");
        }

        List<NurseUserFamily> nurseUserFamilyList = nurseUserFamilyService.list(new QueryWrapper<NurseUserFamily>().eq("user_id", nurseUser.getId()).eq("status", "1"));

        List<NurseUserAddr> nurseUserAddrList = nurseUserAddrService.list(new QueryWrapper<NurseUserAddr>().eq("user_id", nurseUser.getId()).orderByDesc("is_default").orderByAsc("create_time"));

        List<NurseHomeAddr> nurseHomeAddrList = nurseHomeAddrService.list(new QueryWrapper<NurseHomeAddr>().eq("user_id", nurseUser.getId()).orderByDesc("is_default").orderByAsc("create_time"));

        NurseUserPage nurseUserPage = new NurseUserPage();

        //nurseUser.setPhone(SensitiveInfoUtil.getEncodeData(nurseUser.getPhone(), SensitiveEnum.MOBILE_PHONE));
        //nurseUser.setIdcard(SensitiveInfoUtil.getEncodeData(nurseUser.getIdcard(), SensitiveEnum.ID_CARD));

        BeanUtils.copyProperties(nurseUser, nurseUserPage);

        nurseUserPage.setNurseUserAddrList(nurseUserAddrList);
        nurseUserPage.setNurseUserFamilyList(nurseUserFamilyList);
        nurseUserPage.setNurseHomeAddrList(nurseHomeAddrList);

        return Result.OK(nurseUserPage);

    }

    /**
     * 编辑
     *
     * @param nurseUserPage
     * @return
     */
    @AutoLog(value = "用户管理-微信编辑")
    @ApiOperation(value = "用户管理-微信编辑", notes = "用户管理-微信编辑")
    //@RequiresPermissions("nurse_user:nurse_user:edit")
    @RequestMapping(value = "/editByWeChat", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editByWeChat(@RequestBody NurseUserPage nurseUserPage) {
        NurseUser nurseUser = new NurseUser();
        BeanUtils.copyProperties(nurseUserPage, nurseUser);
        NurseUser nurseUserEntity = nurseUserService.getById(nurseUser.getId());
        if (nurseUserEntity == null) {
            return Result.error("未找到对应数据");
        }
        //取消加密
       // nurseUser.setPhone(SensitiveInfoUtil.getDecodeData(nurseUser.getPhone()));
       // nurseUser.setIdcard(SensitiveInfoUtil.getDecodeData(nurseUser.getIdcard()));

        Long count = nurseUserAddrService.count(new QueryWrapper<NurseUserAddr>().eq("user_id", nurseUser.getId()));

        if (count == 0 && !nurseUserPage.getNurseUserFamilyList().isEmpty()) {
            NurseUserAddr NurseUserAddr = new NurseUserAddr();
            BeanUtils.copyProperties(nurseUserPage.getNurseUserFamilyList().get(0), NurseUserAddr);
            NurseUserAddr.setIsDefault("true");
            NurseUserAddr.setId(null);
            List<NurseUserAddr> list = new ArrayList<>();
            list.add(NurseUserAddr);
            nurseUserPage.setNurseUserAddrList(list);
        }
        nurseUserService.updateById(nurseUser);

        nurseUserFamilyService.saveOrUpdateBatch(nurseUserPage.getNurseUserFamilyList());

        nurseUserAddrService.saveOrUpdateBatch(nurseUserPage.getNurseUserAddrList());

        return Result.OK("编辑成功!");
    }


    /**
     * 设置默认医院
     *
     * @param userId
     * @param defaultHospital
     * @param defaultHospitalName
     * @return
     */
    @AutoLog(value = "用户管理-设置默认医院")
    @ApiOperation(value = "用户管理-设置默认医院", notes = "用户管理-设置默认医院")
    @GetMapping(value = "/editDefaultHospital")
    public Result<?> editDefaultHospital(@RequestParam(name = "userId") String userId, @RequestParam(name = "defaultHospital") String defaultHospital, @RequestParam(name = "defaultHospitalName") String defaultHospitalName) {
        NurseUser nurseUserEntity = nurseUserService.getById(userId);
        if (nurseUserEntity == null) {
            return Result.error("未找到对应数据");
        }
        nurseUserEntity.setDefaultHospital(defaultHospital);
        nurseUserEntity.setDefaultHospitalName(defaultHospitalName);
        nurseUserService.updateById(nurseUserEntity);
        return Result.OK("设置成功");
    }




    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param nurseUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "用户管理-分页列表查询")
    @ApiOperation(value = "用户管理-分页列表查询", notes = "用户管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<NurseUser>> queryPageList(NurseUser nurseUser, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<NurseUser> queryWrapper = QueryGenerator.initQueryWrapper(nurseUser, req.getParameterMap());
        Page<NurseUser> page = new Page<NurseUser>(pageNo, pageSize);
        IPage<NurseUser> pageList = nurseUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 添加
     *
     * @param newNurseUser
     * @return
     */
    @AutoLog(value = "用户管理-添加")
    @ApiOperation(value = "用户管理-添加", notes = "用户管理-添加")
    //@RequiresPermissions("nurse_user:nurse_user:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody NurseUser newNurseUser) {
        if (redisUtil.hasKey(newNurseUser.getOpenid() + "_phone")) {
            newNurseUser.setPhone(redisUtil.get(newNurseUser.getOpenid() + "_phone").toString());
        }

        NurseUser nurseUser = nurseUserService.getOne(new QueryWrapper<NurseUser>().eq("openid", newNurseUser.getOpenid()));

        if (nurseUser == null) {
            newNurseUser.setDefaultHospital("1");
            newNurseUser.setDefaultHospitalName("南宁安好护理站");
            newNurseUser.setPort("0");
            nurseUserService.save(newNurseUser);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUser
     * @return
     */
    @AutoLog(value = "用户管理-编辑")
    @ApiOperation(value = "用户管理-编辑", notes = "用户管理-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody NurseUser nurseUser) {
        nurseUserService.updateById(nurseUser);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户管理-通过id删除")
    @ApiOperation(value = "用户管理-通过id删除", notes = "用户管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        nurseUserService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户管理-批量删除")
    @ApiOperation(value = "用户管理-批量删除", notes = "用户管理-批量删除")
    @RequiresPermissions("nurse_user:nurse_user:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequiresPermissions("nurse_user:nurse_user:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, NurseUser nurseUser) {
        return super.exportXls(request, nurseUser, NurseUser.class, "用户管理");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequiresPermissions("nurse_user:nurse_user:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, NurseUser.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-用户监护人-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "用户监护人-通过主表ID查询")
    @ApiOperation(value = "用户监护人-通过主表ID查询", notes = "用户监护人-通过主表ID查询")
    @GetMapping(value = "/listNurseUserFamilyByMainId")
    public Result<IPage<NurseUserFamily>> listNurseUserFamilyByMainId(NurseUserFamily nurseUserFamily, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<NurseUserFamily> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserFamily, req.getParameterMap());
        Page<NurseUserFamily> page = new Page<NurseUserFamily>(pageNo, pageSize);
        IPage<NurseUserFamily> pageList = nurseUserFamilyService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserFamily
     * @return
     */
    @AutoLog(value = "用户监护人-添加")
    @ApiOperation(value = "用户监护人-添加", notes = "用户监护人-添加")
    @PostMapping(value = "/addNurseUserFamily")
    public Result<String> addNurseUserFamily(@RequestBody NurseUserFamily nurseUserFamily) {
        nurseUserFamilyService.save(nurseUserFamily);
        // 保存之后根据id调用数据库序列SELECT seq_anfineid(id) AS anfineid重新写入本条数据的anfineid
        nurseUserFamilyService.updateAnfineidById(nurseUserFamily.getId());
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param nurseUserFamily
     * @return
     */
    @AutoLog(value = "用户监护人-添加")
    @ApiOperation(value = "用户监护人-添加", notes = "用户监护人-添加")
    @PostMapping(value = "/addNurseUserFamily1")
    public Result<String> addNurseUserFamily1(@RequestBody NurseUserFamily nurseUserFamily) {

        QueryWrapper<NurseUserFamily> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", nurseUserFamily.getUserId()).eq("idcard", nurseUserFamily.getIdcard());

        List<NurseUserFamily> list = nurseUserFamilyService.list(queryWrapper);

        if(oConvertUtils.isNotEmpty(list)){
            nurseUserFamilyService.removeBatchByIds(list);
        }
        nurseUserFamilyService.save(nurseUserFamily);
        return Result.OK("添加成功！");

    }

    /**
     * 编辑
     *
     * @param nurseUserFamily
     * @return
     */
    @AutoLog(value = "用户监护人-编辑")
    @ApiOperation(value = "用户监护人-编辑", notes = "用户监护人-编辑")
    @RequestMapping(value = "/editNurseUserFamily", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editNurseUserFamily(@RequestBody NurseUserFamily nurseUserFamily) {
        nurseUserFamilyService.updateById(nurseUserFamily);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户监护人-通过id删除")
    @ApiOperation(value = "用户监护人-通过id删除", notes = "用户监护人-通过id删除")
    @DeleteMapping(value = "/deleteNurseUserFamily")
    public Result<String> deleteNurseUserFamily(@RequestParam(name = "id", required = true) String id) {
        nurseUserFamilyService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户监护人-批量删除")
    @ApiOperation(value = "用户监护人-批量删除", notes = "用户监护人-批量删除")
    @DeleteMapping(value = "/deleteBatchNurseUserFamily")
    public Result<String> deleteBatchNurseUserFamily(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserFamilyService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportNurseUserFamily")
    public ModelAndView exportNurseUserFamily(HttpServletRequest request, NurseUserFamily nurseUserFamily) {
        // Step.1 组装查询条件
        QueryWrapper<NurseUserFamily> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserFamily, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<NurseUserFamily> pageList = nurseUserFamilyService.list(queryWrapper);
        List<NurseUserFamily> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户监护人");
        mv.addObject(NormalExcelConstants.CLASS, NurseUserFamily.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户监护人报表", "导出人:" + sysUser.getRealname(), "用户监护人"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importNurseUserFamily/{mainId}")
    public Result<?> importNurseUserFamily(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<NurseUserFamily> list = ExcelImportUtil.importExcel(file.getInputStream(), NurseUserFamily.class, params);
                for (NurseUserFamily temp : list) {
                    temp.setUserId(mainId);
                }
                long start = System.currentTimeMillis();
                nurseUserFamilyService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-用户监护人-end----------------------------------------------*/

    /*--------------------------------子表处理-用户地址-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "用户地址-通过主表ID查询")
    @ApiOperation(value = "用户地址-通过主表ID查询", notes = "用户地址-通过主表ID查询")
    @GetMapping(value = "/listNurseUserAddrByMainId")
    public Result<IPage<NurseUserAddr>> listNurseUserAddrByMainId(NurseUserAddr nurseUserAddr, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<NurseUserAddr> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserAddr, req.getParameterMap());
        Page<NurseUserAddr> page = new Page<NurseUserAddr>(pageNo, pageSize);
        IPage<NurseUserAddr> pageList = nurseUserAddrService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserAddr
     * @return
     */
    @AutoLog(value = "用户地址-添加")
    @ApiOperation(value = "用户地址-添加", notes = "用户地址-添加")
    @PostMapping(value = "/addNurseUserAddr")
    public Result<String> addNurseUserAddr(@RequestBody NurseUserAddr nurseUserAddr) {
        nurseUserAddrService.save(nurseUserAddr);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUserAddr
     * @return
     */
    @AutoLog(value = "用户地址-编辑")
    @ApiOperation(value = "用户地址-编辑", notes = "用户地址-编辑")
    @RequestMapping(value = "/editNurseUserAddr", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editNurseUserAddr(@RequestBody NurseUserAddr nurseUserAddr) {
        nurseUserAddrService.updateById(nurseUserAddr);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户地址-通过id删除")
    @ApiOperation(value = "用户地址-通过id删除", notes = "用户地址-通过id删除")
    @DeleteMapping(value = "/deleteNurseUserAddr")
    public Result<String> deleteNurseUserAddr(@RequestParam(name = "id", required = true) String id) {
        nurseUserAddrService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户地址-批量删除")
    @ApiOperation(value = "用户地址-批量删除", notes = "用户地址-批量删除")
    @DeleteMapping(value = "/deleteBatchNurseUserAddr")
    public Result<String> deleteBatchNurseUserAddr(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserAddrService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportNurseUserAddr")
    public ModelAndView exportNurseUserAddr(HttpServletRequest request, NurseUserAddr nurseUserAddr) {
        // Step.1 组装查询条件
        QueryWrapper<NurseUserAddr> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserAddr, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<NurseUserAddr> pageList = nurseUserAddrService.list(queryWrapper);
        List<NurseUserAddr> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户地址");
        mv.addObject(NormalExcelConstants.CLASS, NurseUserAddr.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户地址报表", "导出人:" + sysUser.getRealname(), "用户地址"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importNurseUserAddr/{mainId}")
    public Result<?> importNurseUserAddr(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<NurseUserAddr> list = ExcelImportUtil.importExcel(file.getInputStream(), NurseUserAddr.class, params);
                for (NurseUserAddr temp : list) {
                    temp.setUserId(mainId);
                }
                long start = System.currentTimeMillis();
                nurseUserAddrService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-用户地址-end----------------------------------------------*/

    /*--------------------------------子表处理-用户积分-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "用户积分-通过主表ID查询")
    @ApiOperation(value = "用户积分-通过主表ID查询", notes = "用户积分-通过主表ID查询")
    @GetMapping(value = "/listNurseUserIntegralByMainId")
    public Result<IPage<NurseUserIntegral>> listNurseUserIntegralByMainId(NurseUserIntegral nurseUserIntegral, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<NurseUserIntegral> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserIntegral, req.getParameterMap());
        Page<NurseUserIntegral> page = new Page<NurseUserIntegral>(pageNo, pageSize);
        IPage<NurseUserIntegral> pageList = nurseUserIntegralService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserIntegral
     * @return
     */
    @AutoLog(value = "用户积分-添加")
    @ApiOperation(value = "用户积分-添加", notes = "用户积分-添加")
    @PostMapping(value = "/addNurseUserIntegral")
    public Result<String> addNurseUserIntegral(@RequestBody NurseUserIntegral nurseUserIntegral) {
        nurseUserIntegralService.save(nurseUserIntegral);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUserIntegral
     * @return
     */
    @AutoLog(value = "用户积分-编辑")
    @ApiOperation(value = "用户积分-编辑", notes = "用户积分-编辑")
    @RequestMapping(value = "/editNurseUserIntegral", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editNurseUserIntegral(@RequestBody NurseUserIntegral nurseUserIntegral) {
        nurseUserIntegralService.updateById(nurseUserIntegral);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户积分-通过id删除")
    @ApiOperation(value = "用户积分-通过id删除", notes = "用户积分-通过id删除")
    @DeleteMapping(value = "/deleteNurseUserIntegral")
    public Result<String> deleteNurseUserIntegral(@RequestParam(name = "id", required = true) String id) {
        nurseUserIntegralService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户积分-批量删除")
    @ApiOperation(value = "用户积分-批量删除", notes = "用户积分-批量删除")
    @DeleteMapping(value = "/deleteBatchNurseUserIntegral")
    public Result<String> deleteBatchNurseUserIntegral(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserIntegralService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @AutoLog(value = "清除用户数据")
    @ApiOperation(value = "清除用户数据", notes = "清除用户数据")
    @DeleteMapping(value = "/clearUserInfo")
    public Result<String> clearUserInfo(@RequestParam(name = "id", required = true) String id,
                                        @RequestParam(name = "openid", required = true) String openid) {
        this.nurseUserService.clearUserInfo(id, openid);
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportNurseUserIntegral")
    public ModelAndView exportNurseUserIntegral(HttpServletRequest request, NurseUserIntegral nurseUserIntegral) {
        // Step.1 组装查询条件
        QueryWrapper<NurseUserIntegral> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserIntegral, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<NurseUserIntegral> pageList = nurseUserIntegralService.list(queryWrapper);
        List<NurseUserIntegral> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户积分");
        mv.addObject(NormalExcelConstants.CLASS, NurseUserIntegral.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户积分报表", "导出人:" + sysUser.getRealname(), "用户积分"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importNurseUserIntegral/{mainId}")
    public Result<?> importNurseUserIntegral(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<NurseUserIntegral> list = ExcelImportUtil.importExcel(file.getInputStream(), NurseUserIntegral.class, params);
                for (NurseUserIntegral temp : list) {
                    temp.setUserId(mainId);
                }
                long start = System.currentTimeMillis();
                nurseUserIntegralService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-用户积分-end----------------------------------------------*/

    /*--------------------------------子表处理-用户优惠劵-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "用户优惠劵-通过主表ID查询")
    @ApiOperation(value = "用户优惠劵-通过主表ID查询", notes = "用户优惠劵-通过主表ID查询")
    @GetMapping(value = "/listNurseUserSpecialByMainId")
    public Result<IPage<NurseUserSpecial>> listNurseUserSpecialByMainId(NurseUserSpecial nurseUserSpecial, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<NurseUserSpecial> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserSpecial, req.getParameterMap());
        Page<NurseUserSpecial> page = new Page<NurseUserSpecial>(pageNo, pageSize);
        IPage<NurseUserSpecial> pageList = nurseUserSpecialService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserSpecial
     * @return
     */
    @AutoLog(value = "用户优惠劵-添加")
    @ApiOperation(value = "用户优惠劵-添加", notes = "用户优惠劵-添加")
    @PostMapping(value = "/addNurseUserSpecial")
    public Result<String> addNurseUserSpecial(@RequestBody NurseUserSpecial nurseUserSpecial) {
        nurseUserSpecialService.save(nurseUserSpecial);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUserSpecial
     * @return
     */
    @AutoLog(value = "用户优惠劵-编辑")
    @ApiOperation(value = "用户优惠劵-编辑", notes = "用户优惠劵-编辑")
    @RequestMapping(value = "/editNurseUserSpecial", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editNurseUserSpecial(@RequestBody NurseUserSpecial nurseUserSpecial) {
        nurseUserSpecialService.updateById(nurseUserSpecial);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户优惠劵-通过id删除")
    @ApiOperation(value = "用户优惠劵-通过id删除", notes = "用户优惠劵-通过id删除")
    @DeleteMapping(value = "/deleteNurseUserSpecial")
    public Result<String> deleteNurseUserSpecial(@RequestParam(name = "id", required = true) String id) {
        nurseUserSpecialService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户优惠劵-批量删除")
    @ApiOperation(value = "用户优惠劵-批量删除", notes = "用户优惠劵-批量删除")
    @DeleteMapping(value = "/deleteBatchNurseUserSpecial")
    public Result<String> deleteBatchNurseUserSpecial(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserSpecialService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportNurseUserSpecial")
    public ModelAndView exportNurseUserSpecial(HttpServletRequest request, NurseUserSpecial nurseUserSpecial) {
        // Step.1 组装查询条件
        QueryWrapper<NurseUserSpecial> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserSpecial, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<NurseUserSpecial> pageList = nurseUserSpecialService.list(queryWrapper);
        List<NurseUserSpecial> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户优惠劵");
        mv.addObject(NormalExcelConstants.CLASS, NurseUserSpecial.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户优惠劵报表", "导出人:" + sysUser.getRealname(), "用户优惠劵"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importNurseUserSpecial/{mainId}")
    public Result<?> importNurseUserSpecial(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<NurseUserSpecial> list = ExcelImportUtil.importExcel(file.getInputStream(), NurseUserSpecial.class, params);
                for (NurseUserSpecial temp : list) {
                    temp.setUserId(mainId);
                }
                long start = System.currentTimeMillis();
                nurseUserSpecialService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }


    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private final RestTemplate restTemplate = new RestTemplate();
    @AutoLog(value = "用户登录-解密微信手机号密文")
    @ApiOperation(value = "用户登录-解密微信手机号密文", notes = "用户登录-解密微信手机号密文")
    @PostMapping("/WeChatPhoneNumberDecrypter")
    public Result<?> WeChatPhoneNumberDecrypter(@RequestBody Map<String, Object> data){
        System.out.println("WeChatPhoneNumberDecrypter-data: " + data);
        String result = "";
        String phoneNumber = "";
//        getSessionKey((String) data.get("code"));
        try{
            result = Decrypt(
                    getSessionKey((String) data.get("code")),
                    (String) data.get("encryptedData"),
                    (String) data.get("iv")
            );
            System.out.println("result: " + result);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(result, Map.class);
            phoneNumber = (String) map.get("phoneNumber");
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.ok(phoneNumber);
    }
    public String Decrypt(String code, String encryptedData, String iv) throws Exception{
        // Base64 解码
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
        byte[] sessionKeyBytes = Base64.getDecoder().decode(code);
        byte[] ivBytes = Base64.getDecoder().decode(iv);
        System.out.println("sessionKeyBytes: " + sessionKeyBytes.length);
        // 设置AES密钥和初始化向量
        SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        // 创建Cipher实例并初始化
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        // 解密
        byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

        // 将解密后的字节转换为字符串
        String result = new String(decryptedBytes, StandardCharsets.UTF_8);
        return result;
    }
    public String getSessionKey(String code){
        System.out.println("getSessionKey-code: " + code);
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, appsecret, code
        );
        String response = restTemplate.getForObject(url, String.class);
        Map<String, Object> result = new HashMap<>();
        try {
            result = new ObjectMapper().readValue(response, Map.class);
            System.out.println("getSessionKey-result: " + result);
            return (String) result.get("session_key");
        } catch (Exception e) {
            result.put("error", "解析响应失败");
            return null;
        }
    }

    /*--------------------------------子表处理-用户优惠劵-end----------------------------------------------*/

//    @AutoLog(value = "用户管理-wss用户登录")
//    @ApiOperation(value = "wss用户登录", notes = "wss用户登录")
//    @GetMapping(value = "/clientLogin")
//    public Result<?> clientLogin(@RequestParam(name = "username") String username,
//                                 @RequestParam(name = "password") String password) {
//
//        username = SensitiveInfoUtil.getDecodeData(username);
//
//        password = SensitiveInfoUtil.getDecodeData(password);
//
//        log.info("username:{}password:{}",username,password);
//
//
//        JSONObject req = new JSONObject();
//
//        req.put("username", username);
//        req.put("password", password);
//
//        JSONObject res = RestUtil.post(loginUrl, req);
//
//        res = res.getJSONObject("result");
//
//        if (oConvertUtils.isEmpty(res)) {
//            return Result.error("登录失败！未请求到用户信息");
//        }
//
//        String token = res.getString("token");
//
//        if (oConvertUtils.isEmpty(token)) {
//            return Result.error("登录失败！未请求到token");
//        }:：


//        return Result.OK(token);
//    }


}
